<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;

class Billing extends BaseController
{
    /**
     * 获取计费方案列表
     */
    public function getBillingPlans()
    {
        try {
            $plans = Db::name('sysbillingplan')
                ->select();

            return json([
                'code' => 200,
                'data' => $plans,
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 根据车辆获取计费方案（包含默认选中）
     */
    public function getBillingPlansByCar()
    {
        $carNumber = $this->request->param('car_number', '');

        if (empty($carNumber)) {
            return json(['code' => 400, 'msg' => '车牌号不能为空']);
        }

        try {
            // 获取车辆信息中的计费项目名称
            $carInfo = Db::name('sysidcardinfo')
                ->field('JiFeiXiangName')
                ->where('CarNomber|IDCardNomber', $carNumber)
                ->find();

            if (!$carInfo) {
                return json(['code' => 404, 'msg' => '车辆信息不存在']);
            }

            // 获取所有计费方案
            $plans = Db::name('sysbillingplan')->field('id,HourW1,jifeimoney,JifeiXiangName')->select();

            // 标记默认选中的方案
            $defaultPlanName = $carInfo['JiFeiXiangName'] ?? '';


            return json([
                'code' => 200,
                'data' => [
                    'plans' => $plans,
                    'car_default_plan' => $defaultPlanName
                ],
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 根据计费方案名称获取详情
     */
    public function getPlanDetail()
    {
        $planName = $this->request->param('plan_name', '');

        if (empty($planName)) {
            return json(['code' => 400, 'msg' => '计费方案名称不能为空']);
        }

        try {
            $plan = Db::name('sysbillingplan')
                ->where('JifeiXiangName', $planName)
                ->find();

            if (!$plan) {
                return json(['code' => 404, 'msg' => '计费方案不存在']);
            }

            return json([
                'code' => 200,
                'data' => $plan,
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 计算租车费用
     */
    public function calculateRentFee()
    {
        $planName = $this->request->param('plan_name', '');
        $hours = $this->request->param('hours', 0);

        if (empty($planName) || $hours <= 0) {
            return json(['code' => 400, 'msg' => '参数不完整']);
        }

        try {
            // 获取计费方案
            $plan = Db::name('sysbillingplan')
                ->where('JifeiXiangName', $planName)
                ->find();

            if (!$plan) {
                return json(['code' => 404, 'msg' => '计费方案不存在']);
            }

            $hourUnit = $plan['HourW1'] ?? 0.5; // 计费时间单位（小时）
            $unitPrice = $plan['jifeimoney'] ?? 0; // 单位价格

            // 计算费用（向上取整，按计费单位计算）
            $units = ceil($hours / $hourUnit);
            $totalFee = $units * $unitPrice;

            $result = [
                'plan_name' => $planName,
                'hours' => $hours,
                'hour_unit' => $hourUnit,
                'unit_price' => $unitPrice,
                'billing_units' => $units,
                'total_fee' => $totalFee
            ];

            return json([
                'code' => 200,
                'data' => $result,
                'msg' => '计算成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }
}
